const router = require('koa-router')()
const svgCaptcha = require('svg-captcha');
const jwt = require('jsonwebtoken');
const myKey = "lvshuxiaochengxu765"

// 登录
router.post('/login', async (ctx, next) => {
    let sql = "select * from manage"
    let result = await ctx.db.EXCUTE(sql);
    const managename = ctx.request.body.userName
    const pwd = ctx.request.body.pwd
    if (ctx.request.body.captcha == ctx.session.captcha) {
        for (var i = 0; i < result.length; i++) {
            if (managename == result[i].managename && pwd == result[i].password) {
                let token = jwt.sign({ "managename": managename }, myKey);
                ctx.body = { data: result[i], "code": 200, "token": token, "msg": "success" };
                break;
            } else {
                ctx.body = { "code": 200, 'msg': "uperr" }
            }
        }
    } else {
        ctx.body = { 'code': 200, 'msg': 'error' }
    }
})

// 验证码
router.get('/captcha', async (ctx, next) => {
    var captcha = svgCaptcha.create();
    ctx.session.captcha = captcha.text;
    ctx.body = { data: captcha.data, status: 200 };
})

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Hello Koa 2!'
    })
})

router.get('/string', async (ctx, next) => {
    ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
    ctx.body = {
        title: 'koa2 json'
    }
})

module.exports = router
